package ch.fusun.baron.basic.command;

import ch.fusun.baron.city.City;
import ch.fusun.baron.city.api.CityService;
import ch.fusun.baron.core.injection.Configure;
import ch.fusun.baron.core.injection.Inject;
import ch.fusun.baron.player.Dynasty;
import ch.fusun.baron.player.Player;
import ch.fusun.baron.player.api.PlayerService;
import ch.fusun.baron.property.api.PropertyService;
import ch.fusun.baron.unit.Unit;
import ch.fusun.baron.unit.service.UnitService;

/**
 * Command to create a unit in a city
 */
public class CreateUnitCommand extends MoneyTurnCommand {

	@Configure(value = "10")
	private int MONEY;

	@Inject
	private transient UnitService unitService;
	@Inject
	private transient CityService cityService;
	@Inject
	private transient PropertyService propertyService;
	@Inject
	private transient PlayerService playerService;

	private Dynasty dynasty;
	private City city;
	private int numberOfUnits;

	/**
	 * Injection constructor
	 */
	public CreateUnitCommand() {
	}

	/**
	 * @param dynasty
	 *            The player
	 * @param city
	 *            The city
	 * @param numberOfUnits
	 *            The number of units to create
	 */
	public CreateUnitCommand(Dynasty dynasty, City city, int numberOfUnits) {
		this.dynasty = dynasty;
		this.city = city;
		this.numberOfUnits = numberOfUnits;
	}

	@Override
	public boolean isAllowedImpl() {
		return cityBelongsToPlayer()
				&& unitService.getUnits(cityService.getLocation(city))
						.isEmpty();
	}

	private boolean cityBelongsToPlayer() {
		return dynasty.equals(playerService.getDynasty((Player) propertyService
				.getOwnership(propertyService.getOwnership(cityService
						.getLocation(city)))));
	}

	@Override
	public void executeImpl() {
		Unit unit = unitService.createUnit(cityService.getLocation(city),
				numberOfUnits);
		propertyService.setOwnership(dynasty, unit);
	}

	@Override
	protected int getTurnCost() {
		return numberOfUnits;
	}

	@Override
	protected Dynasty getDynasty() {
		return dynasty;
	}

	@Override
	protected int getMoneyCost() {
		return numberOfUnits * MONEY;
	}

}
